if (window.tbk) {
  window.tbk.reinit();
} else {
   window.tbk = {
    initialize: function() {
      // load libraries
      this.loadLibs();
    },
    loadLib: function() {
      this.loadScript(); 
    },
    loadScript: function(script_url) {
      var s = document.createElement('script');
      s.src = script_url;
      s.type = "text/javascript";
      document.getElementsByTagName('body')[0].appendChild(s);
    },
    reinit: function() {
      this.languageApiLoaded();
    },
    loadGoogleApi: function() {
      this.loadScript('http://www.google.com/jsapi?callback=tbk.loadLanguageApi');
    },
    loadLanguageApi: function() {
      google.load("language", "1", {language: 'en', callback: 'tbk.languageApiLoaded'});
    },
    languageApiLoaded: function() {
      // convert all tweets and set title
      //alert('api loaded');; 
       //$('.entry-content').live('mouseover', tbk.addTranslation );
       //$('.msgtxt').live('mouseover', tbk.addTranslation );
      //$('a#search_more, a#results_update, a#more').click(function() {$('.entry-content, .msgtxt').each(tbk.addTranslation);});
      if (jQuery) {
        $('.entry-content, .msgtxt').each(tbk.addTranslation);
      } else {
        $$('.msgtxt').each(tbk.addTranslation);
      }
    },    
    addTranslation: function(evt) {
      elem = $(this);
      if (! $.data(this, 'active.tipsy') || $.data(this, 'active.tipsy').html() == '') {
        // add tipsy
        //elem.die('mouseover', tbk.addTranslation);
        tbk.detectLanguage(elem, elem.html());
      }
    },
    detectLanguage: function(elem, txt) {
       //alert('detecting language for txt ' + txt);
       google.language.detect(txt, function(detect_response) { tbk.translate(elem, txt, detect_response)});
    },
    translate: function(elem, txt, detect_response) {
      //alert('detected language ' + detect_response.language);
      if (!detect_response.error && detect_response.language) {
	if (detect_response.language != 'en') {
          google.language.translate(txt, detect_response.language, 'en', function(translation_response) { tbk.setTipsy(elem, txt, translation_response); });
        }
      } else {
        elem.attr('title', 'Error encountered detecting language for text:' + detect_response.error);
      }
    },
    setTipsy: function(elem, txt, translation_response) {
      var t = 'No translation found for text';
      if (translation_response.translation) {
	t = translation_response.translation;
      } 
      elem.tipsy({gravity: $.fn.tipsy.autoWE});
      elem.attr('title', t);
    }
  };
  tbk.initialize();
}
void(0);
